<template>
  <div class="app-container product-create-container">
    <div class="step-container">
      <el-steps :active="stepActive">
        <el-step title="选择商品品类" />
        <el-step title="填写商品详情" />
        <el-step title="商品发布成功" />
      </el-steps>
    </div>
    <div class="step-content-container">
      <div class="remindNotice">
        <p class="item">1、**********</p>
        <p class="item">2、************</p>
      </div>
      <el-form
        ref="dataForm"
        style="display: flex;  flex-direction: column;   flex: 1;   overflow: auto;"
        class="common-form-with-desc"
        :rules="productRules"
        :model="productRecord"
        label-position="right"
        label-width="120px">
        <template v-if="stepActive===1">
          <el-alert v-if="selectCategoryNames.length>0" style="margin-top:10px" type="success" :closable="false" :description="'您当前选择的商品品类是：'+selectCategoryNames.join(' > ')" />
          <div class="form-container scrollbar-no-width" style="display: flex;;">
            <div class="category-container">
              <div class="category-item scrollbar-no-width">
                <div v-for="item in categoryData" :key="item.id" class="category-li" :class="{'active':firstCategoryId===item.id}" @click="loadNextCategory(item,1)">
                  <div class="category-name">{{ item.categoryName }}</div>
                  <div class="category-icon"><i class="el-icon-arrow-right" /></div>
                </div>
              </div>
              <div v-if="secondCategoryData.length>0" class="category-item scrollbar-no-width">
                <div v-for="item in secondCategoryData" :key="item.id" class="category-li" :class="{'active':secondCategoryId===item.id}" @click="loadNextCategory(item,2)">
                  <div class="category-name">{{ item.categoryName }}</div>
                  <div class="category-icon"><i class="el-icon-arrow-right" /></div>
                </div>
              </div>
              <div v-if="thirdCategoryData.length>0" class="category-item scrollbar-no-width">
                <div v-for="item in thirdCategoryData" :key="item.id" class="category-li" :class="{'active':thirdCategoryId===item.id}" @click="loadNextCategory(item,3)">
                  <div class="category-name">{{ item.categoryName }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="processToolbar">
            <el-button type="primary" @click="handleNextCreateStep">下一步</el-button>
          </div>
        </template>
        <template v-if="stepActive===2">
          <div class="form-container scrollbar-no-width">

            <div class="common-title m-b-20"><h2 class="bold">基本信息</h2></div>
            <el-form-item label="商品品类:">{{ selectCategoryNames.join(' > ') }} </el-form-item>
            <el-form-item label="SN:" prop="sn">
              <el-input v-model="productRecord.sn" maxlength="12" :disabled="status==='update'" show-word-limit placeholder="请输入商品SN" clearable>
                <template slot="append"><span class="common-cursor" @click="handleGenerateSN">生成</span></template>
              </el-input>
            </el-form-item>
            <el-form-item label="商品名称:" prop="name">
              <el-input v-model="productRecord.name" maxlength="100" show-word-limit placeholder="请输入商品名称" clearable />
            </el-form-item>
            <el-form-item label="售价:" prop="price">
              <el-input-number v-model="productRecord.price" :precision="2" :step="0.1" :min="0" placeholder="请输入售价" />
            </el-form-item>
            <el-form-item label="成本价:" prop="costPrice">
              <el-input-number v-model="productRecord.costPrice" :precision="2" :step="0.1" :min="0" placeholder="请输入成本价" />
            </el-form-item>
            <el-form-item label="商品卖点:" prop="introduce">
              <el-input
                v-model="productRecord.introduce"
                :rows="5"
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入商品卖点(限200字以内)" />
            </el-form-item>
            <el-form-item label="商品品牌:" prop="brandId">
              <el-select v-model="productRecord.brandId" clearable filterable placeholder="请选择品牌">
                <el-option
                  v-for="item in bindBrands"
                  :key="item.id"
                  :label="item.brandName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
            <div class="common-title m-b-20"><h2 class="bold">商品交易信息</h2></div>
            <el-form-item label="是否在售:" prop="isSale">
              <el-radio-group v-model="productRecord.isSale">
                <el-radio :label="1">在售</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="计量单位:" prop="unit">
              <el-input v-model="productRecord.unit" maxlength="1" show-word-limit placeholder="请输入计量单位" clearable />
            </el-form-item>
            <el-form-item label="库存:" prop="totalInventory">
              <el-input-number v-model="productRecord.totalInventory" :min="0" placeholder="请输入库存" />
            </el-form-item>
            <div class="common-title m-b-20"><h2 class="bold">商品图片</h2></div>
            <el-form-item label="缩略图:" prop="smallImage">
              <single-image-upload v-model="productRecord.smallImage" :catalog="constants.FILE_CATALOG_PRODUCT" />
            </el-form-item>
            <el-form-item label="轮播图:" prop="largeImage">
              <MultipleImageUpload v-model="productRecord.largeImage" :limit="5" :catalog="constants.FILE_CATALOG_EXAMPLE" />
            </el-form-item>
            <div class="common-title m-b-20"><h2 class="bold">商品详情描述</h2></div>
            <el-form-item label="图文描述:" prop="imageText">
              <Editor v-model="productRecord.imageText" :catalog="constants.FILE_CATALOG_EXAMPLE" height="1000px" />
            </el-form-item>
          </div>
          <div class="processToolbar">
            <el-button type="primary" @click="handleBeforeCategoryStep">上一步</el-button>
            <el-button type="primary" @click="status==='create'?createData():updateData()">保存</el-button>
          </div>
        </template>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      stepActive: 1,
      status: 'create',
      categoryData: [],
      secondCategoryData: [],
      thirdCategoryData: [],
      selectCategoryNames: [],
      firstCategoryId: null,
      secondCategoryId: null,
      thirdCategoryId: null,
      bindBrands: [],
      productRecord: {},
      productRules: {
        sn: [
          { required: true, message: '请输入产品SN码', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        smallImage: [
          { required: true, message: '请上传商品缩略图', trigger: 'blur' }
        ],
        largeImage: [
          { required: true, message: '请上传商品轮播图', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入售价', trigger: 'blur' }
        ],
        costPrice: [
          { required: true, message: '请输入成本价', trigger: 'blur' }
        ],
        isSale: [
          { required: true, message: '请选择是否在售', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入计量单位', trigger: 'blur' }
        ],
        totalInventory: [
          { required: true, message: '请输入库存', trigger: 'blur' }
        ],
        imageText: [
          { required: true, message: '请输入图文描述', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    $route: function(val) {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      var id = this.$route.query.id
      if (id) {
        this.loading = this.$loading({
          lock: true,
          text: '正在加载数据...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.handleUpdate(id)
        this.stepActive = 2
      } else {
        this.stepActive = 1
        this.categoryTree()
        this.handleCreate()
      }
    },
    handleGoBack() {
      this.$router.push({ path: '/product' })
      const view = this.$route
      delete view.icon
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {})
    },
    async categoryTree() {
      this.categoryData = []
      this.categoryData = await this.$store.dispatch('productCategoryTreeTable', { })
    },
    loadNextCategory(item, level) {
      if (level === 1) {
        if (!item.children) {
          this.$modal.msgWarning('暂无下级')
          return
        }
        this.firstCategoryId = item.id
        this.secondCategoryData = item.children
        this.selectCategoryNames = [item.categoryName]
        this.thirdCategoryData = []
      }
      if (level === 2) {
        if (!item.children) {
          this.$modal.msgWarning('暂无下级')
          return
        }
        this.secondCategoryId = item.id
        this.thirdCategoryData = item.children
        this.selectCategoryNames = [this.selectCategoryNames[0], item.categoryName]
      }
      if (level === 3) {
        this.thirdCategoryId = item.id
        this.selectCategoryNames = [this.selectCategoryNames[0], this.selectCategoryNames[1], item.categoryName]
      }
    },
    handleGenerateSN() {
      this.productRecord = {
        ...this.productRecord,
        sn: this.T.randomNumber(12)
      }
    },
    handleBeforeCategoryStep() {
      this.stepActive = 1
      this.secondCategoryData = []
      this.thirdCategoryData = []
      this.selectCategoryNames = []
      this.firstCategoryId = null
      this.secondCategoryId = null
      this.thirdCategoryId = null
      this.categoryTree()
    },
    handleNextCreateStep() {
      if (this.selectCategoryNames.length !== 3) {
        this.$modal.msgWarning('请选择商品品类')
        return
      }
      this.stepActive = 2
      this.handleLoadBindBrand()
    },
    handleLoadBindBrand() {
      this.$store.dispatch('productCategoryListBindBrand', this.thirdCategoryId).then(res => {
        this.bindBrands = res
      })
    },
    /* 新增*/
    handleCreate() {
      this.productRecord = {
        isSale: 1,
        costPrice: 0,
        price: 0,
        totalInventory: 0
      }
      this.status = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      console.log(this.productRecord)
      this.productRecord = {
        ...this.productRecord,
        categoryId: this.thirdCategoryId
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('productSave', this.productRecord).then(response => {
            this.$confirm('商品发布成功', '提示', {
              confirmButtonText: '继续添加',
              cancelButtonText: '商品列表',
              type: 'warning'
            }).then(() => {
              this.$router.push({ name: 'productCreate', query: { }})
              this.init()
            }).catch(() => {
              this.handleGoBack()
            })
          }).catch(() => {
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(id) {
      this.status = 'update'
      this.$store.dispatch('productGetDetailsById', id).then(res => {
        this.productRecord = res
        if (this.loading) {
          this.loading.close()
        }
        this.thirdCategoryId = res.categoryId
        this.handleLoadBindBrand()
        this.selectCategoryNames = res._fullCategoryNames
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }).catch((_) => {
        if (this.loading) {
          this.loading.close()
        }
      })
    },
    updateData() {
      console.log(this.productRecord)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.productRecord)
          delete tempData._fullCategoryNames
          delete tempData._fullCategoryIds
          this.$store.dispatch('productUpdate', tempData).then(response => {
            this.$confirm('商品修改成功', '提示', {
              confirmButtonText: '继续添加',
              cancelButtonText: '商品列表',
              type: 'warning'
            }).then(() => {
              this.$router.push({ name: 'productCreate', query: { }})
              this.init()
            }).catch(() => {
              this.handleGoBack()
            })
          }).catch(() => {
          })
        }
      })
    }
  }
}
</script>
<style  lang="scss" scoped>
  .common-form-with-desc{
    .el-button{
      width: auto;
    }
  }
  .category-container{
    background-color: #ededed;
    border-radius: 8px;
    padding: 10px;
    display: flex;
    flex-direction: row;
    flex: 1;
    .category-item{
      width: 260px;
      padding: 12px 8px;
      background: #fff;
      border-radius: 8px;
      margin-right: 15px;
      overflow: auto;
      .category-li{
        line-height: 20px;
        cursor: pointer;
        padding: 10px 5px;
        color: #333;
        font-size: 12px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      }
      .category-li.active{
        color: var(--color-primary);
      }
    }
  }
  .step-container{
    width: 100%;
    background-color: #fff;
    overflow: hidden;
    .el-steps{
      margin-top: 10px;
      margin-left: 29px;
    }
  }
  .step-content-container{
    flex: 1;
    background-color: #fff;
    height: 100%;
    padding: 15px;
    overflow: auto;
    display: flex;
    flex-direction: column;
  }
  .remindNotice {
    line-height: 20px;
    background: #e1ecff;
    border: 1px solid var(--color-primary);
    border-radius: 2px;
    color: #333;
    font-size: 12px;
    text-align: justify;
    padding: 10px 20px;
    margin-top: 10px;
    .item{
      padding: 0px;
      margin: 0px;
    }
  }
  .form-container{
    background-color: #fff;
    font-weight: 400;
    font-style: normal;
    margin-top: 10px;
    flex: 1;
    overflow: auto;
  }
  .processToolbar {
    padding-top: 20px;
    background-color: #fff;
    text-align: center;
    border-top: 1px solid #F2F6FC;
  }
</style>
